package org.sws.trigger.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.sws.domain.activity.service.quota.IActivitySkuStockService;
import org.sws.types.event.BaseEvent;

import javax.annotation.Resource;

/**
 * @Author sws
 * @Date 2025/3/20 09:53
 * @description: 抽奖活动库存为0事件消费
 */
@Slf4j
@Component
public class ActivitySkuStockZeroCustomer {
    @Value("${spring.rabbitmq.topic.activity_sku_stock_zero}")
    private String topic;

    @Resource
    private IActivitySkuStockService skuStock;
    @RabbitListener(queuesToDeclare = @Queue("${spring.rabbitmq.topic.activity_sku_stock_zero}"))
    public void listener(String eventMessage){
        try {
            BaseEvent.EventMessage<Long> parsed = JSON.parseObject(eventMessage, new TypeReference<BaseEvent.EventMessage<Long>>() {
            }.getType());
            Long sku = parsed.getData();
            // 更新库存
            skuStock.clearActivitySkuStock(sku);
            // 清空队列
            skuStock.clearQueueValue(sku);
            log.info("消费活动sku库存消耗为0消息完成，topic: {} message: {}", topic, eventMessage);
        } catch (Exception e) {
            log.error("监听活动sku库存消耗为0消息，消费失败 topic: {} message: {}", topic, eventMessage);
            throw e;
        }
    }
}
